from db.sql import engine
from db.sql import Edge
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import InvalidRequestError
from sqlalchemy.sql.expression import func, select
import os

DBSession = sessionmaker(bind=engine)
session = DBSession()


def insert(object):
    try:
        if type(object) == list:
            for i in object:
                session.add(i)
        else:
            session.add(object)
        session.commit()
        return True
    except InvalidRequestError:
        session.rollback()
    except Exception as e:
        print(e)
        return False


def delete(object):
    try:
        if type(object) == list:
            for o in object:
                session.delete(o)
                session.commit()
            else:
                session.delete(object)
                session.commit()
        return True
    except InvalidRequestError:
        session.rollback()
    except Exception as e:
        print(e)
        return False


def query_by_path(path):
    return session.query(Edge).filter(Edge.path == path).first()


if __name__ == '__main__':
    for i in session.query(Edge).all():
        i.path.replace('\\', '/')
    session.commit()
